/**
 * Created by ysl on 2017/8/24.
 */
import React, { Component } from 'react';
import {
    StyleSheet,
    View,
    FlatList,
    Text,
    Button,
    Dimensions,
    TouchableOpacity
    } from 'react-native';
const { height, width } = Dimensions.get('window');
var ITEM_HEIGHT = 100;


export default class FlatListExample extends Component {

    constructor(props) {
        super(props);

        this.state = {
            refreshing: false,
            list: this.props.list,
        };

    }

    _renderItem = (item) => {
        let item1 = item;
        var txt = '第' + item1.index + '个' + ' title=' + item1.item.title;
        var bgColor = item1.index % 2 == 0 ? 'red' : 'blue';
        return (
            <TouchableOpacity onPress={() => {
                alert(txt);
            } }>
                <Text
                    style={[{ flex: 1, height: ITEM_HEIGHT, backgroundColor: bgColor, width: width / 2 }, styles.txt]}>{txt}</Text>
            </TouchableOpacity>
        )
    }

    _separator = () => {
        if (this.props.ItemSeparatorComponent != undefined)
            return this.props.ItemSeparatorComponent;
        else
            return <View style={{ height: 2, backgroundColor: 'transparent' }}/>;
    }

    setMyList(myList) {
        if (myList != null) {
            this.setState({
                list: myList,
            });
        }
    }

    render() {
        var data = [];
        for (var i = 0; i < 20; i++) {
            data.push({key: i, title: i + ''});
        }

        return (
           <FlatList
                ref={(flatList) => this._flatList = flatList}
                ItemSeparatorComponent={this._separator()}//设置item的分割线
                renderItem={this.props.renderItem} //设置item
                numColumns={this.props.numColumns}//设置每行item的个数
                getItemLayout={(data, index) => (
                        //如果我们知道行高可以用此方法节省动态计算行高的开销。
                            { length: this.props.itemHight, offset: (this.props.itemHight + 2) * index, index }
                        ) }
                data={this.state.list}>
            </FlatList>
        );
    }
}

const styles = StyleSheet.create({
    txt: {
        textAlign: 'center',
        textAlignVertical: 'center',
        color: 'white',
        fontSize: 30,
    }
});
